
'use strict';
import Base from './base.js';

export default class extends Base {

	async indexAction(){
		//取出菜单项
		this.meta_title = '连锁列表';
		return this.display();
	}

	async shoplistAction(){
		if (this.isPost) {
			let pages = this.post('pages');
			let limits = this.post('limits');

			let list = await this.model('or_department')
					.alias('d')
					.field('d.id, d.name as dname, d.isdisable, d.orcode, di.begintime, di.endtime, a.phone, a.name as aname, a.remarks,(select count(e.id) from `think_or_department` e  where e.pid = d.id) as gnum, di.addtime')
					.join('`think_or_department_info` di on di.departmentid=d.id')
					.join('`think_or_admin` a on a.departmentid=d.id and a.ismain=1')
					.where({'d.floor': 0})
					.page(pages, limits)
					.order('d.id DESC')
					.countSelect();

			return this.json(list);
		}
		return this.display();
	}

	async addAction(){
		if (this.isPost) {

			let data = this.post();
			let time = Math.round(new Date().valueOf()/1000);

			if (!(data.dname || data.orcode)) {
				return this.fail('请填写完整数据！');
			}

			// 判断手机号和机构码是否被使用
			let use_code = await this.model('or_department').where('orcode="'+data.orcode+'" OR name="'+data.name+'"').find();
			let use_phone = await this.model('or_admin').where({username: data.username}).find();
			if (!think.isEmpty(use_code)) {
				return this.fail('机构码或机构名称重复');
			}
			if (!think.isEmpty(use_phone)) {
				return this.fail('手机号码已被使用');
			}

			let model = this.model('or_department');
			await model.transaction(async () => {
				try {
					let addone = {
						name: data.dname,
						orcode: data.orcode
					}
					let departmentid = await model.add(addone);
					if (!departmentid) {
						await model.rollback();
						return this.fail('添加机构失败');
					}

					let addtwo = {
						departmentid: departmentid,
						begintime: data.begintime,
						endtime: data.endtime,
						gnum: data.gnum,
						addtime: time,
					}
					let dinfo = await this.model('or_department_info').db(model.db()).add(addtwo);
					if (!dinfo) {
						await model.rollback();
						return this.fail('添加机构信息失败');
					}

					let addthree = {
						username: data.username,
						password: think.md5(data.username),
						name: data.user,
						departmentid: departmentid,
						groupid: 1,
						phone: data.username,
						ismain: 1
					}
					let ainfo = await this.model('or_admin').db(model.db()).add(addthree);
					if (!ainfo) {
						await model.rollback();
						return this.fail('添加机构总管理员失败');
					}


					let gcate = await this.model('or_guestcategory').db(model.db()).add({departmentid: departmentid});

					if (!gcate) {
						await model.rollback();
						return this.fail('添加机构客户分类失败');
					}

					await model.commit();
					return this.success('添加机构成功');
				} catch(e) {
					console.log(e);
					await model.rollback();
					return this.fail('添加机构失败');
				}
			})
		} else{
			return this.display();
		}
	}

	async editshopAction(){
		if(this.isPost){
			let data = this.post();
			//判断数据
			if(!data.name || !data.orcode){
				return this.fail('请填写完整数据！');
			}
			//判断编码是否重复
			let is_exist = await this.model('or_department').where({orcode:data.orcode, floor: 0, id: ["!=",data.id]}).find();
			if(!think.isEmpty(is_exist)){
				return this.fail('此编码已经存在');
			}

			let model = this.model('or_department');
			await model.transaction(async ()=>{
				try {
					let updateinfo = {
						departmentid: data.id,
						begintime: data.begintime,
						endtime: data.endtime,
						validity: data.validity,
						gnum: data.gnum,
						addtime: Math.round(new Date().valueOf()/1000)
					}

					/*
					* 判断当前机构是否有信息
					* 如果没有就新添加一体
					* 如果有，则更新这条数据
					*/

					let whetherExist = await this.model('or_department_info').db(model.db()).where({departmentid: data.id}).find();

					if (!think.isEmpty(whetherExist)) {
						let gxinfo = await this.model('or_department_info').db(model.db()).where({departmentid: data.id}).update(updateinfo);
						if (!gxinfo) {
							await model.rollback();
							return this.fail('更新机构基本信息失败');
						}
					} else {
						let adinfo = await this.model('or_department_info').db(model.db()).add(updateinfo);
						if (!adinfo) {
							await model.rollback();
							return this.fail('添加机构基本信息失败');
						}
					}
					
					let upinfo = {
						name: data.name,
						orcode: data.orcode
					}

					let gx = await model.where({id: data.id}).update(upinfo);

					if (!gx) {
						await model.rollback();
						return this.fail('更改失败2');
					}

					let isguestcate = await this.model('or_guestcategory').db(model.db()).where({departmentid: data.id}).find();
					if (think.isEmpty(isguestcate)) {
						let addguestcate = await this.model('or_guestcategory').db(model.db()).add({departmentid: data.id});
						if (!addguestcate) {
							await model.rollback();
							return this.fail('添加机构客户分类失败');
						}
					}

					await model.commit();
					return this.success('更改成功');
				} catch(e) {
					console.log(e);
					await model.rollback();
					return this.fail('更改失败');
				}
			})
		} else {
			let id = this.get('id');
			let row = await this.model('or_department')
					.alias('d')
					.field('d.id, d.name, d.orcode, i.endtime, i.gnum')
					.join('`think_or_department_info` i on i.departmentid=d.id')
					.where({'d.id':id})
					.find();

			this.assign('row',row);
			return this.display();
		}
	}
	
	async edituserAction(){
		if(this.isPost){
			let data = this.post();
			//判断数据
			if(!data.name || !data.username){
				return this.fail('请填写完整数据');
			}

			if (data.id * 1) {
				let repeat = await this.model('or_admin').where({username: data.username, id: ['!=', data.id]}).find();
				if (!think.isEmpty(repeat)) {
					return this.fail('手机号重复');
				}
				let uptwo = {
					name: data.name,
					username: data.username,
					password: think.md5(data.username),
					phone: data.username,
					remarks: data.remarks,
					groupid: 1
				}
				let res = await this.model('or_admin').where({id: data.id}).update(uptwo);
				return res?this.success('更改成功'):this.fail('更改失败');
			} else {
				let cunzai = await this.model('or_admin').where({username: data.username}).find();
				if (!think.isEmpty(cunzai)) {
					return this.fail('手机号已被注册');
				}
				let addone = {
					name: data.name,
					username: data.username,
					password: think.md5(data.username),
					departmentid: data.departmentid,
					phone: data.username,
					remarks: data.remarks,
					ismain: 1,
					groupid: 1
				}
				let tian = await this.model('or_admin').add(addone);

				return tian?this.success('添加联系人成功'):this.fail('添加联系人失败');
			}
			//判断编码是否重复
			let is_exist = await this.model('or_admin').where({username: data.username, id: ["!=", data.id]}).find();
			if(!think.isEmpty(is_exist)){
				return this.fail('手机号已经存在');
			}

			data.password = think.md5(data.username);
			data.phone = data.username;

			let is_save = await this.model('or_admin').update(data);
			return is_save?this.success('编辑成功'):this.fail('更改失败');
		}else{
			let id = this.get('id');
			let row = await this.model('or_admin').field('id, username, name, remarks, departmentid').where({departmentid:id, ismain: 1}).find();
			if (think.isEmpty(row)) {
				row = {
					id: 0,
					username: '',
					name: '',
					remarks: '',
					departmentid: id,
				}
			}
			this.assign('row',row);
			return this.display();
		}	
	}

	async unstopAction(){
		let id = this.post('id');
		let status = this.post('status');

		let model = this.model('or_department');
		await model.transaction(async ()=>{
			try {
				let dting = await model.where({id: id}).update({isdisable: status});
				let ating = await this.model('or_admin').db(model.db()).where({departmentid:id, ismain: 1}).update({isdisable: status});

				if (dting && ating) {
					await model.commit();
					return status*1?this.success('停用成功'):this.success('启用成功');
				}
				await model.rollback();
				return status*1?this.fail('停用失败'):this.fail('启用失败');
			} catch(e) {
				console.log(e);
				await model.rollback();
				return status?this.fail('停用失败'):this.fail('启用失败');
			}
		})
	}

	// 广播
  async broadcastAction(){
  	if (this.isGet) {
  		let data = await this.model('or_broadcast').select();
  		for (var i = 0; i < data.length; i++) {
  			if (data[i].content.length > 40) {
  				data[i].content = data[i].content.substring(0, 40)+'...【详情点击编辑查看】';
  			}
  		}
  		this.assign('broadcastlist',data);
  	} else {
  		let status = this.post();
  		let odata = await this.model('or_broadcast').where({id:status.id}).update({isbroadcast:status.isbroadcast});
  		return odata?this.success('更改成功'):this.fail('更改失败');
  	}
  	return this.display();
  }

  async addbroadcastAction(){
  	this.meta_title = '新增广播';
  	return this.display();
  }

  async editbroadcastAction(){
		if (this.isPost) {
			let data = this.post();
			console.log(data);
			let time = new Date();
			let yy = time.getFullYear();
			let mm = time.getMonth()<9?'0'+(time.getMonth()+1):time.getMonth();
			let dd = time.getDate()<10?'0'+time.getDate():time.getDate();
			let updatetime = yy + '-' + mm + '-' + dd;
			let res = await this.model('or_broadcast').where({id:parseInt(data.id)}).update({
				content : data.content,
				updatetime : updatetime
			});
			return res?this.success('编辑成功！'):this.fail('编辑失败！');
		} else {
			let id = this.get();
			console.log(id);
			let res = await this.model('or_broadcast').where({id:parseInt(id.id)}).find();
			this.assign('res',res);
			return this.display();
		}
  }

}